//
//  CharacterLimitBehaviour.swift
//  StoryboardObject
//
//  Created by CaryaLiu on 2021/4/26.
//

import UIKit

class CharacterLimitBehaviour: HIKBehaviour {

    @IBOutlet weak var textView: UITextView! {
        didSet {
            updateCountLabel()
        }
    }
    @IBOutlet weak var countLabel: UILabel! {
        didSet {
            updateCountLabel()
        }
    }
    
    @IBInspectable var maxCount: UInt = 0
    @IBInspectable var hideKeyboardOnReturn: Bool = false
    
    override func awakeFromNib() {
        super.awakeFromNib()
        assert(maxCount != 0)
    }
}

extension CharacterLimitBehaviour: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        if let selectedRange = textView.markedTextRange,
           textView.position(from: selectedRange.start, offset: 0) != nil {
            return
        }
        if  textView.text.count > maxCount {
            let startIndex = textView.text.startIndex
            let endIndex = textView.text.index(startIndex, offsetBy: Int(maxCount))
            textView.text = String(textView.text[startIndex..<endIndex])
        }
        updateCountLabel()
    }
    
    func updateCountLabel() {
        guard textView != nil, countLabel != nil else {
            return
        }
        if textView.text.count > maxCount {
            countLabel.text = "\(maxCount)/\(maxCount)"
        } else {
            countLabel.text = "\(textView.text.count)/\(maxCount)"
        }
        sendActions(for: .valueChanged)
    }
}
